const Base = require('./base.js');

module.exports = class extends Base {
    indexAction() {
        return this.display();
    }

    /**
     * 分页加载表格数据
     * @returns json字符串
     */
    async listAction() {
        let userinfo = await this.assign('userinfo');           //拿到登录信息
        let arr = ['tb_user_role ON id=user_id',
            'RIGHT JOIN tb_role ON tb_role.id=role_id'];
        let role = await this.model('user').join(arr).where({user_id: userinfo.id}).page(this.get('page'), this.get('limit')).find();       //根据登录信息id拿到对应权限
        let roleAuthority = role.authority;
        let model = this.model('role');
        let str = `authority !='ROLE_SUPER_ADMIN'  and  authority !='${roleAuthority}'`;

        let permission_name = this.get('permission_name');
        if (!think.isEmpty(permission_name)) {
            str = `authority !='ROLE_SUPER_ADMIN' and  authority !='${roleAuthority}' and permission_name like '%${permission_name}%'`;
        }
        let data = await model.where(str).page(this.get('page'), this.get('limit')).countSelect();
        return this.jsonPage(data);
    }


    /**
     * 添加
     * @returns  返回code
     */
    async addAction() {
        let model = this.model('role');
        if (this.isPost) {
            try {
                let data = this.post();
                data.authority = 'ROLE_CE_SHI_JIAO_SE';
                data.date_created = new Date();
                let success = await model.add(data);
                return this.json(success);
            } catch (e) {
                //违反唯一约束，角色名重复,返回false
                return this.json(0);
            }
        } else {
            return this.display();
        }
    }

    async deleteAction() {
        let model = this.model('role');
        let data = this.post();
        if (this.isPost) {
            let success = await model.where({id: ['=', data.id]}).delete();
            return this.json(success);
        } else {
            return this.fail('500', '请求格式错误!');
        }
    }

    async updateAction() {
        let model = this.model('request_map');
        let whereMap = {};
        let config_attribute_true = [];
        if (this.isPost) {
            let roleArray = JSON.parse(this.post('roleId'));       //接收传过来的数组
            let authority = this.post('authority');
            whereMap.config_attribute = ['like', `%${authority}%`];
            let whereStr = `config_attribute != 'permitAll'`;
            let data = await model.where(whereStr).select();          //查到所有数据
            let copyArray = data.slice();
            for (let i = 0; i < data.length; i++) {
                for (let j = 0; j < roleArray.length; j++) {
                    if (data[i].id == roleArray[j]) {
                        config_attribute_true.push(data[i]);        //把选中的权限放入数组
                        copyArray.splice(copyArray.indexOf(data[i]), 1);        //没选中的权限放入数组
                    }
                }
            }
            let config_attribute = '';
            for (let i = 0; i < copyArray.length; i++) {
                //查询已经取消的权限
                if (copyArray[i].config_attribute.indexOf(authority) > -1) {          //判断查询的权限是否包含用户编辑的权限
                    let splitArray = copyArray[i].config_attribute.split(',');       //根据逗号分割字符
                    for (let j = 0; j < splitArray.length; j++) {
                        if (splitArray[j] != authority) {           //判断当前获取的全下跟编辑的用户权限是否相同
                            //当不是最后一个权限的时候
                            if (j + 1 == splitArray.length - 1) {           //判断下一个是不是最后一个权限
                                if (splitArray[j + 1] != authority) {           //如果下个权限是最后一个并且不等于编辑用户的权限
                                    config_attribute += splitArray[j] + ',';       //用逗号分隔
                                } else {
                                    config_attribute += splitArray[j];              //不用逗号分隔
                                }
                            } else {
                                config_attribute += splitArray[j] + ',';
                            }
                        }
                    }
                    try {
                        model.where({id: copyArray[i].id}).update({config_attribute: config_attribute});
                        config_attribute = ''
                    } catch (e) {
                        return this.json(0);
                    }
                }
            }
            //修改选中的权限
            for (let i = 0; i < config_attribute_true.length; i++) {
                if (config_attribute_true[i].config_attribute.indexOf(authority) <= -1) {
                    let splitArray = config_attribute_true[i].config_attribute.split(',');
                    for (let j = 0; j < splitArray.length; j++) {
                        config_attribute += splitArray[j] + ',';
                    }
                    config_attribute += authority;
                    try {
                        model.where({id: config_attribute_true[i].id}).update({config_attribute: config_attribute});
                        config_attribute = ''
                    } catch (e) {
                        return this.json(0);
                    }
                }
            }
            return this.json(1);
        } else {
            let authority = this.get('authority');
            this.assign('roleAuthority', authority);
            return this.display();
        }
    }


    /**
     * 加载树形菜单权限
     * @returns json
     */
    async getRoleMenuAction() {
        let authority = this.get('authority');
        let model = this.model('request_map');
        let whereMap = {};
        whereMap.config_attribute = ['!=', 'permitAll'];
        let roleJson = await model.where(whereMap).select();
        let treeJson = {};
        let data = [];
        let childArr = [];
        for (var i = 0; i < roleJson.length; i++) {         //循环查询权限显示父节点
            if (roleJson[i].menu_name == '系统设置' && authority != 'ROLE_SUPER_ADMIN') {
                continue;
            }
            if (roleJson[i].menu_id == null) {
                treeJson.id = roleJson[i].id;
                treeJson.text = roleJson[i].menu_name;
                treeJson.state = {opened: 'true'};
                if (roleJson[i].config_attribute.indexOf(authority) >= 0) {      //判断是否拥有该权限
                    treeJson.state = {selected: true};
                }
                for (let j = i; j < roleJson.length; j++) {
                    if (j < roleJson.length - 1) {
                        if (roleJson[i].id == roleJson[j + 1].menu_id) {  //获取父节点下的子节点
                            if (roleJson[j + 1].config_attribute.indexOf(authority) >= 0) {      //判断是否拥有该权限
                                childArr.push({
                                    id: roleJson[j + 1].id,
                                    text: roleJson[j + 1].menu_name,
                                    icon: 'none',
                                    state: {selected: 'true'}
                                });
                            } else {
                                childArr.push({
                                    id: roleJson[j + 1].id,
                                    text: roleJson[j + 1].menu_name,
                                    icon: 'none'
                                });
                            }
                        }
                    }
                }
                treeJson.children = childArr;
                childArr = [];
                data.push(treeJson);
                treeJson = {};
            }

        }
        return this.json(data);
    }


    // async getRoleMenuAction() {
    //
    // }

}
;


